#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sqlite3.h>
#include "sqlite3.h"
#include "tcp_server.h"

int callback(void* data, int argc, char** value, char** name)
{
	if(argc!=0)
	*(int *)data=1;
	return 0;
}

int sqlite3_init(char * pathname, sqlite3** db)
{
	int ret= sqlite3_open(pathname, db);
	if(ret != SQLITE_OK)
	{
		printf("%s\n",sqlite3_errstr(ret));
		return -1;
	}
	return 0;
}

int user_login(char* name, char* passwd,sqlite3* db)
{
	char sql[200];
	sprintf(sql,"SELECT * FROM users WHERE name='%s' AND passwd='%s';", name, passwd);
	
	char* err;
	int flag =0;
	if(SQLITE_OK!=sqlite3_exec(db, sql, callback, (void*)&flag,&err))
	{
		printf("查询失败 %s\n",err);
		return -1;
	}
	if(flag==0)
	{
		return -1;
	}
	else
	{
		return 0;
	}
}

int user_register(char* name, char* passwd,sqlite3* db)
{
	char sql[200];
	sprintf(sql,"INSERT INTO users (name, passwd) VALUES('%s', '%s');",name, passwd);
	
	char* err;
	int flag =0;
	if(SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &err))
	{
		printf("插入失败 %s\n",err);
		return -1;
	}
	return 0;
}

int user_update(char* name, char* passwd,char* oldname,sqlite3* db)
{
	char sql[200];
	sprintf(sql,"UPDATE users SET name='%s',passwd='%s' WHERE name='%s' ", name, passwd, oldname);
	
	char* err;
	int flag =0;
	if(SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &err))
	{
		printf("更新失败 %s\n",err);
		return -1;
	}
	return 0;
}

int user_delete(char* name, char* passwd,sqlite3* db)
{
	char sql[200];
	sprintf(sql,"DELETE FROM users WHERE name='%s' and passwd='%s';", name,passwd);
	
	char* err;
	int flag =0;
	if(SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &err))
	{
		printf("删除失败 %s\n",err);
		return -1;
	}
	return 0;
}


